package com.cysion.study.ui

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.View
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.cysion.other.color
import com.cysion.study.R
import com.cysion.study.adapter.POrderRefundAdapter
import com.cysion.study.entity.FamilyeduAppointEntity
import com.cysion.study.entity.POrderDetailEntity
import com.cysion.study.entity.ProcessList
import com.cysion.study.helper.UserCache
import com.cysion.study.ktbox.Box
import com.cysion.study.ktbox.base.BaseActivity
import com.cysion.study.ktbox.base.ITEM_CLICK
import com.cysion.study.ktbox.image.RoundTransform
import com.cysion.study.ktbox.net.BaseResponseRx
import com.cysion.study.ktbox.net.ErrorHandler
import com.cysion.study.ktbox.utils.darkTextTheme
import com.cysion.study.net.ApiClient
import com.cysion.study.ui.pteacher.PCourseDetailActivity
import com.cysion.study.uibox.bar.TopBar
import com.cysion.study.uibox.dialog.Alert
import com.cysion.study.uibox.dialog.CONFIRM
import com.cysion.study.widget.ShowToast
import com.cysion.study.widget.UIHelper
import com.cysion.targetfun._subscribe
import kotlinx.android.synthetic.main.activity_porder_detail.*
import kotlinx.android.synthetic.main.order_detail_info.*
import kotlinx.android.synthetic.main.order_detail_pro.*
import kotlinx.android.synthetic.main.order_detail_refund.*
import kotlinx.android.synthetic.main.order_sub_info.*

class POrderDetailActivity : BaseActivity(), View.OnClickListener {
    override fun getLayoutId(): Int {
        return R.layout.activity_porder_detail
    }

    private var orderId = ""
    private var byType = ""////byType1 根据订单号请求订单详情，2订单id请求订单详情
    override fun initView() {
        byType = intent.extras.getString("byType")
        orderId = intent.extras.getString("orderId")

        darkTextTheme(color(R.color.white))
        topbar.apply {
            setTitleBackColor(color(R.color.white))
            setTitle("订单详情")
            setOnTopBarClickListener { obj, pos ->
                if (pos == TopBar.Pos.LEFT) {
                    finish()
                }
            }
        }

        initRecyclerView()
        tv_btn_left.setOnClickListener(this)
        tv_btn_right.setOnClickListener(this)
        tv_refuse.setOnClickListener(this)
        tv_agree.setOnClickListener(this)
        tv_address.setOnClickListener(this)
        tv_phone.setOnClickListener(this)
    }


    //退款进度list
    private lateinit var mAdapter: POrderRefundAdapter
    private val dataList: MutableList<ProcessList> = mutableListOf()
    //初始化列表
    private fun initRecyclerView() {
        rv_list.isNestedScrollingEnabled = false
        mAdapter = POrderRefundAdapter(dataList, Box.context)
        rv_list.adapter = mAdapter
        rv_list.layoutManager = LinearLayoutManager(Box.context)
        mAdapter.setOnTypeClickListener { obj, position, flag ->
            if (flag == ITEM_CLICK) {//
            }
        }
    }

    override fun initData() {
        super.initData()
        //byType1 根据订单号请求订单详情，2订单id请求订单详情
        if (byType == "1") {
            getDetailByOrderNo()
        }else if (byType == "2") {
            getDetailByOrderId()
        }
    }

    //2订单id请求订单详情
    private fun getDetailByOrderId() {
        Alert.loading(this)
        ApiClient.api.orderDetail(UserCache.token, orderId).compose(
            BaseResponseRx.validateToMain()
        )
            ._subscribe {
                _onNext {
                    Alert.close()
                    initV(it)
                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                }
            }
    }

    //根据订单号请求订单详情
    private fun getDetailByOrderNo() {
        Alert.loading(this)
        ApiClient.api.orderDetailByNo(UserCache.token, orderId).compose(
            BaseResponseRx.validateToMain()
        )
            ._subscribe {
                _onNext {
                    Alert.close()
                    initV(it)
                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                }
            }
    }

    private var infolongitude=""
    private var infolatitude=""
    private var address=""
    private var phone=""
    private var orderObj: POrderDetailEntity=POrderDetailEntity()
    private fun initV(obj: POrderDetailEntity) {
        orderObj=obj
        Glide.with(this).load(obj.infoStuHeadImage)
            .apply(RequestOptions.placeholderOf(R.mipmap.place_holder_big))
            .apply(RequestOptions.bitmapTransform(RoundTransform(6)))
            .into(iv_img)
        tv_name.text = obj.infoStuNickName
        tv_phone.text = obj.phone
        tv_address.text=obj.infosupplement
        infolongitude=obj.infolongitude
        infolatitude=obj.infolatitude
        address=obj.infosupplement
        phone=obj.phone
        /*if (TextUtils.isEmpty(obj.infosupplement)) {
            tv_address.visibility=View.GONE
        }*/
        //订单信息
        tv_back_money.text = "申请退款金额：" + obj.payMoney
        tv_order_no.text = "订单号：" + obj.orderNo
        tv_phone_order.text = "手机号：" + obj.phone
        tv_time.text = "下单时间：" + obj.createTime
        tv_pay_time.text = "支付时间：" + obj.payTime
        tv_num.text = "数量：" + obj.quanty
        tv_price.text = "课时单价：" + obj.price
        tv_total_money.text = "总价：" + obj.totalMoney
        tv_pay_money.text = "实付：" + obj.payMoney

        //预约信息
        tv_sub_phone.text = "手机号：" + obj.infoFamilyLink
        tv_content.text = "补习内容：" + obj.infoCourseContent
        tv_want_time.text = "期望时间：" + obj.infoCourseTime
        tv_course_type.text = "补习方式：" + obj.infoTypes
        tv_sub_time.text = "预约时间：" + obj.infoCreateTime


        //订单状态：0.待付款 1.已付款 2.已完成（已评价）3、待评价 4.申请退款中，5.已拒绝退款，
        // 6.已同意退款 7.交易关闭，8、申请客服介入中； 9、客服同意退款 10、客服拒绝退款
        // 11、原路退回中，12、原路退款成功 13、原路退款失败，14、家教订单待确认；
        if (obj.status == "0") {
            tv_status.text = "待付款"
        } else if (obj.status == "1") {
            tv_status.text = "服务中"
        } else if (obj.status == "2") {
            tv_status.text = "已完成"
        } else if (obj.status == "3") {
            tv_status.text = "待评价"
        } else if (obj.status == "4") {
            tv_status.text = "申请退款中"
        } else if (obj.status == "5") {
            tv_status.text = "已拒绝退款"
        } else if (obj.status == "6") {
            tv_status.text = "已同意退款"
        } else if (obj.status == "7") {
            tv_status.text = "交易关闭"
        } else if (obj.status == "8") {
            tv_status.text = "申请客服介入中"
        } else if (obj.status == "9") {
            tv_status.text = "客服同意退款"
        } else if (obj.status == "10") {
            tv_status.text = "客服拒绝退款"
        } else if (obj.status == "11") {
            tv_status.text = "原路退回中"
        } else if (obj.status == "12") {
            tv_status.text = "原路退款成功"
        } else if (obj.status == "13") {
            tv_status.text = "原路退款失败"
        } else if (obj.status == "14") {
            tv_status.text = "待确认"
        }


        //订单信息(ll_order_info)
        //预约信息(ll_sub)
        //退款视图按钮(ll_back_money)
        //退款进度(ll_back_p)
        //左按钮(tv_btn_left)
        //右按钮(tv_btn_right)

        //已关闭视图
        if (obj.status == "7") {
            ll_order_info.visibility = View.VISIBLE
            ll_sub.visibility = View.VISIBLE
            tv_btn_right.text = "课程管理"
        }
        //待付款视图： 预约信息、关闭订单按钮、缴费提醒按钮
        if (obj.status == "0") {
            ll_sub.visibility = View.VISIBLE
            tv_btn_left.visibility = View.VISIBLE
            tv_btn_left.text = "关闭订单"
            tv_btn_right.text = "缴费提醒"
        }
        //已付款=服务中视图：订单信息、预约信息
        if (obj.status == "1") {//已付款
            ll_order_info.visibility = View.VISIBLE
            ll_sub.visibility = View.VISIBLE
        }
        //申请退款视图： 拒绝 同意按钮(ll_back_money)、订单信息、预约信息、课程管理按钮
        if (obj.status == "4") {//申请退款
            ll_back_money.visibility = View.VISIBLE
            ll_order_info.visibility = View.VISIBLE
            ll_sub.visibility = View.VISIBLE
            tv_btn_right.text = "课程管理"
        }

        //退款 拒绝同意视图：退款进度(ll_back_p)、订单信息、预约信息、授课记录按钮
        if (obj.status == "5" || obj.status == "6") {//
            ll_back_p.visibility = View.VISIBLE
            ll_order_info.visibility = View.VISIBLE
            ll_sub.visibility = View.VISIBLE
            tv_btn_right.text = "授课记录"

            getRefundProcess(orderId)//获取退款进度
        }
        //待确认视图：预约信息、关闭订单按钮、发送缴费申请 按钮
        if (obj.status == "14") {//
            ll_sub.visibility = View.VISIBLE
            tv_btn_left.visibility = View.VISIBLE
            tv_btn_left.text = "关闭订单"
            tv_btn_right.text = "发送缴费申请"
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_address -> {
                if (TextUtils.isEmpty(address)) {
//                    ShowToast("")
                    return
                }
                UIHelper.goToBaidu(self, infolatitude, infolongitude, address)
            }
            R.id.tv_phone -> {
                //拨打电话
                val intent = Intent()
                intent.action = Intent.ACTION_DIAL//dial是拨号的意思
                intent.data = Uri.parse("tel:" + phone)//这个tel不能改，后面的数字可以随便改
                startActivity(intent)
            }
            R.id.tv_btn_left -> {//左按钮
                //关闭订单
                closeOrder()
            }
            R.id.tv_btn_right -> {//右按钮
                if (tv_btn_right.text.toString() == "课程管理") {
                    var bundle = Bundle()
                    bundle.putSerializable("objectId",orderObj.objectId)//
                    UIHelper.jump(self, PCourseDetailActivity::class.java,bundle)
                } else if (tv_btn_right.text.toString() == "缴费提醒") {
                    sendOrder()

                } else if (tv_btn_right.text.toString() == "授课记录") {
                    var bundle = Bundle()
                    bundle.putSerializable("objectId",orderObj.objectId)//
                    UIHelper.jump(self, PCourseDetailActivity::class.java,bundle)

                } else if (tv_btn_right.text.toString() == "发送缴费申请") {
                    sendOrder()
                }
            }
            R.id.tv_refuse -> {//拒绝
                Alert.cancelCourse(this, "拒绝退款", "请输入拒绝理由", "", "拒绝") { confirm, num ->
                    if (confirm == CONFIRM) {
                        if (TextUtils.isEmpty(num)) {
                            ShowToast("请输入拒绝理由")
                            return@cancelCourse
                        }
                        delRefund("2", num)
                    }
                }
            }
            R.id.tv_agree -> {//同意
                Alert.cancelCourse(this, "同意退款", "请输入同意理由", "", "同意") { confirm, num ->
                    if (confirm == CONFIRM) {

                        delRefund("1", "")
                    }
                }
            }
        }
    }


    //发送缴费申请 缴费提醒
    private fun sendOrder() {
        Alert.loading(this)
        ApiClient.api.sendConfirmAppoint(orderId, UserCache.token).compose(
            BaseResponseRx.validateToMain()
        )
            ._subscribe {
                _onNext {
                    Alert.close()
                    ShowToast("发送成功")
                    initData()
                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                }
            }

    }

    //关闭订单
    private fun closeOrder() {
        Alert.loading(this)
        ApiClient.api.ordersClose(orderId, UserCache.token).compose(
            BaseResponseRx.validateToMain()
        )
            ._subscribe {
                _onNext {
                    Alert.close()
                    ShowToast("关闭成功")
                    initData()
                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                }
            }

    }


    //查询退款进度
    private fun getRefundProcess(orderId: String) {
        ApiClient.api.refundProcess(UserCache.token, orderId).compose(
            BaseResponseRx.validateToMain()
        )
            ._subscribe {
                _onNext {
                    Alert.close()
                    dataList.clear()
                    dataList.addAll(it.processList)
                    mAdapter.notifyDataSetChanged()
                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                }
            }
    }

    //拒绝 同意退款
    private fun delRefund(type: String, remark: String) {
        Alert.loading(this)
        ApiClient.api.delRefund(orderId, type, remark, UserCache.token).compose(
            BaseResponseRx.validateToMain()
        )
            ._subscribe {
                _onNext {
                    Alert.close()
                    if (type == "2") {
                        ShowToast("已拒绝退款")
                    } else if (type == "1") {
                        ShowToast("已同意退款")
                    }
                    initData()
                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                }
            }
    }

    override fun closeMvp() {
    }


}
